package com.blockmeta.bbs.businesslibrary.widget.chartview.Layer;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.text.TextUtils;


import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.websocket.Symbol;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.Coordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.MoveCoordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CandleData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CoinChart;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.Core;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.MInteger;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.RetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


class MACDLayer extends BasicLayer
{
	protected final double m_dbNone = Double.MIN_VALUE;
	private int beginIdx;//用于存储第一个指标第一个值的位置
	private String m_macd = "", m_hist = "", m_signal = "";
	private String m_lastMacd = "", m_lastHist = "", m_lastSignal = "";
	private int m_color1 = 0xFF4A86EA, m_color2 = 0xFFFF72A5, m_color3 = 0xFFFFA200, m_color0 = 0xFF808080;
	private int m_fastPeriod = 12, m_slowPeriod = 26, m_signalPeriod = 9;

	public MACDLayer()
	{
		super();
	}

	@Override
	public Coordinate createCoordinate()
	{
		return new MoveCoordinate();
	}

	@Override
	public boolean onCalculateData()
	{

		ArrayList<String> params = new ArrayList<>(Arrays.asList("12", "26", "9"));//FDTStorage.getInstance().getArray(SaveKey.CHART_INDICATOR_MACD + "param", SaveKey.CHART_INDICATOR_PARAM);
		if (params != null)
		{
			m_fastPeriod = !TextUtils.isEmpty(params.get(0)) ? Integer.parseInt(params.get(0)) : 12;
			m_slowPeriod = !TextUtils.isEmpty(params.get(1)) ? Integer.parseInt(params.get(1)) : 26;
			m_signalPeriod = !TextUtils.isEmpty(params.get(2)) ? Integer.parseInt(params.get(2)) : 9;
		}
//		testMacd();
		//获得数据源
		List<CandleData> tDataList = m_callback.getCandleDataList();
		int atleastSize = m_slowPeriod + m_signalPeriod - 2;
		int tListSize = tDataList.size() + atleastSize;
//		FDTLogUtils.d("tingchart","macd tListSize"+tListSize);
		List<CandleData> tList = new ArrayList<CandleData>();
		double[] closes = new double[tListSize];

		if (tListSize <= atleastSize)
		{
			return true;
		}

		for (int ii = 0; ii < tListSize; ii++)
		{
			int index = Math.max(ii - atleastSize, 0);

			closes[ii] = tDataList.get(index).getDbClose();
		}

		//准备计算数组
		double[] macd = new double[tListSize];
		double[] signal = new double[tListSize];
		double[] hist = new double[tListSize];
		MInteger outBegIdx = new MInteger();
		MInteger outNbElement = new MInteger();

		Core taLib = CoinChart.getTaLib();
		RetCode retCode = taLib.macd(0, closes.length - 1, closes, m_fastPeriod, m_slowPeriod, m_signalPeriod, outBegIdx, outNbElement, macd, signal, hist);
		//得到结果数组,结果为有值的部分开始如0.006747350439404443 0.010591595301185919 0.0027601354459569905 -0.03422737187350222 -0.09373321549064784 -0.12136830634374718 -0.12757081986248053 -0.1250403123559245 -0.11954476938285197 -0.04594994628476812 0.009701854832457002 0.06010755762170561 0.09747712313834 0.13895129756983238 0.171272192598785 0.18158545677729165 0.15978420503275714 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
		//outBegIdx为是第几个开始的，outNbElement为有效的数字个数 ，如73个元素，那么outBegIdx为33，outNbElement为40 26-1+9-1=33
		CandleData candle = null;
		if (retCode == RetCode.Success && tListSize > atleastSize)
		{
			for (int i = atleastSize; i < tListSize; i++)//修改数据源
			{
				int index = i - atleastSize;
				candle = tDataList.get(index);
				candle.setDbOpen(macd[index]);
				candle.setDbClose(signal[index]);
				candle.setDbHigh(hist[index]);
			}

			beginIdx = 0; // outBegIdx.value;

			//需要替换把
//			FDTLogUtils.d("tingchart","macd "+" outBegIdx"+outBegIdx.value+" outNbElement"+outNbElement.value);
			return true;
		}
		return false;
	}

	private void testMacd()
	{
		double[] closes = new double[]{16.39, 16.4999, 16.45, 16.43, 16.52, 16.51, 16.423, 16.41, 16.47, 16.45, 16.32, 16.36, 16.34, 16.59, 16.54, 16.52, 16.44, 16.47, 16.5, 16.45, 16.28, 16.07, 16.08, 16.1, 16.1, 16.09, 16.43, 16.4899, 16.59, 16.65, 16.78, 16.86, 16.86, 16.76};
		double[] macd = new double[closes.length];
		double[] signal = new double[closes.length];
		double[] hist = new double[closes.length];
		MInteger outBegIdx = new MInteger();
		MInteger outNbElement = new MInteger();

		Core taLib = CoinChart.getTaLib();
		RetCode retCode = taLib.macd(0, closes.length - 1, closes, 5, 13, 6, outBegIdx, outNbElement, macd, signal, hist);
		StringBuilder builder = new StringBuilder("");
		String s = "";
		for (double value : macd
				)
		{
			builder.append(value + " ");
		}
		s = builder.toString();
	}


	protected int getDataStartIndex()
	{
		return getMoveStartIndex() > beginIdx ? getMoveStartIndex() : beginIdx;
	}

	/**
	 * 获取数据的移动位置
	 *
	 * @return
	 */
	protected int getMoveStartIndex()
	{
		Coordinate tCoordinate = m_callback.getCoordinate();
		if (tCoordinate != null)
		{
			return tCoordinate.getStartIndex();
		}
		return 0;
	}

	@Override
	public Layer.ChartTypeEnum getLayerTypeEnum()
	{
		return Layer.ChartTypeEnum.MACD;
	}

	public List<CandleData> convertDate(List<CandleData> pList)
	{
		return pList;
	}

	@Override
	public void drawYesterClose(Canvas pCanvas, Paint pPaint)
	{
	}

	@Override
	public void onDrawLayer(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
		//获取坐标系
		Coordinate tCoordinate = m_callback.getCoordinate();
		//转化处理数据
		List<CandleData> tDataList = convertDate(m_callback.getCandleDataList());

		//定义初始化文本
		String tTimeText = null;
		String tValueText = null;
		int tXPoint = pPoint.x;


		if (tDataList != null && tDataList.size() > 0)
		{
			int tListSize = tDataList.size();
//			int tStartIndex = tCoordinate.getStartIndex();

			float tXFirstPosition = tCoordinate.getXFirstPosition();
			float tXInterval = tCoordinate.getXInterval();
			float tYFirstposition = tCoordinate.getYFirstPosition();
			// float tYFirstposition = tCoordinate.getYFirstPosition();
			float tYMaxValue = tCoordinate.getMaxValue();
			float tYMinValue = tCoordinate.getMinValue();
			float tYValueDist = tYMaxValue - tYMinValue;
			float tYValueLength = tCoordinate.getValueHeight();
			// float tYValueLength = tCoordinate.getYInterval() *
			// tCoordinate.getYIntervalCount();

			float tCurrentYPosition = 0.f;
			float tTempYPosition = 0.f;
			float tCurrentXPosition = 0.f;
			float tTempXPosition = 0.f;

			float tCurrentYPosition1 = 0.f;
			float tTempYPosition1 = 0.f;
			float tCurrentXPosition1 = 0.f;
			float tTempXPosition1 = 0.f;

			float tCurrentYPosition2 = 0.f;
			float tTempYPosition2 = 0.f;
			float tCurrentXPosition2 = 0.f;
			float tTempXPosition2 = 0.f;

			int tSysUpColor = m_callback.getSysUpColor();
			int tSysDownColor = m_callback.getSysDownColor();
			int tSysEvenColor = m_callback.getSysEvenColor();
			float tBarWidth = Math.min(tXInterval / 3, 25);

			int m_bDigit = m_callback.getDigit();

			Symbol symbol = m_callback.getCoordinate().tSymBol;


			float tLineWidth = 2.f;
			pPaint.setAntiAlias(true);

			boolean tStartDraw = false;

			int tDotColor = BaseApp.getApp().getResources().getColor(R.color.sys_even);
			int tCulOffset = 1;

			float y0Position = tYFirstposition - ((0 - tYMinValue) * tYValueLength / tYValueDist);

			int dataStart = getDataStartIndex(); //tStartIndex + getStartIndex();

			int moveStart = getMoveStartIndex();
			int displayCount = m_callback.getDisplayCount();//获取当前要显示的个数
			int minCount = Math.min(moveStart + displayCount, tListSize);//不能超出数据集宽度
//			FDTLogUtils.d("tingchart",getLayerTypeEnum()+"layer from draw tStartIndex"+dataStart+" to mincount"+minCount);
			if (dataStart > tListSize)//如果数据量不足以算出一个值
			{
				return;
			}
			CandleData candle = null;
			for (int i = dataStart; i < minCount; i++)
			{
				//如果收盘价为空就跳过
				candle = tDataList.get(i);
				if (candle.getDbClose() == m_dbNone || candle.getDbHigh() == m_dbNone || candle.getDbOpen() == m_dbNone)
				{
					continue;
				}

				pPaint.setColor(m_callback.getColor());
				pPaint.setStrokeWidth(tLineWidth);

				float tSignal = (float) candle.getDbClose();
				float tMacd = (float) candle.getDbOpen();
				float tHist = (float) candle.getDbHigh();

				tTempXPosition = tCurrentXPosition;
				tCurrentXPosition = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition = tCurrentYPosition;
				tCurrentYPosition = tYFirstposition - ((tMacd - tYMinValue) * tYValueLength / tYValueDist);

				tTempXPosition1 = tCurrentXPosition1;
				tCurrentXPosition1 = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition1 = tCurrentYPosition1;
				tCurrentYPosition1 = tYFirstposition - ((tSignal - tYMinValue) * tYValueLength / tYValueDist);

				tTempXPosition2 = tCurrentXPosition2;
				tCurrentXPosition2 = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition2 = tCurrentYPosition2;
				tCurrentYPosition2 = tYFirstposition - ((tHist - tYMinValue) * tYValueLength / tYValueDist);


				if (((tCurrentXPosition - tXInterval / 2) <= pPoint.x && pPoint.x < (tCurrentXPosition + tXInterval / 2)) || ((i == minCount - 1) && pPoint.x > tCurrentXPosition + tXInterval / 2))
				{
					float tValueaa = (tYFirstposition - pPoint.y) * tYValueDist / tYValueLength + tYMinValue;
//					FDTLogUtils.d("tingtouch","tValueaa"+tValueaa);

					m_macd = FormatUtil.getFormatString(tMacd, m_bDigit + 1);
					m_hist = FormatUtil.getFormatString(tHist, m_bDigit + 1);
					m_signal = FormatUtil.getFormatString(tSignal, m_bDigit + 1);
					ChartData.ChartPeroid tChartType = m_callback.getChartType();
					tValueText = FormatUtil.getFormatString(tValueaa, m_callback.getDigit());
					tTimeText = getDisplayX(tChartType, tDataList.get(i));

					tXPoint = (int) tCurrentXPosition;
				}

				if (tStartDraw)
				{
					RectF tRectF = tCoordinate.getLayerRectF();

					if (tHist > 0)
					{
						pPaint.setColor(tSysUpColor);
						pCanvas.drawRect(tCurrentXPosition2 - tBarWidth, tCurrentYPosition2, tCurrentXPosition2 + tBarWidth, y0Position, pPaint);
					}
					else
					{
						pPaint.setColor(tSysDownColor);
						pCanvas.drawRect(tCurrentXPosition2 - tBarWidth, y0Position, tCurrentXPosition2 + tBarWidth, tCurrentYPosition2, pPaint);
					}


					pPaint.setColor(m_color1);
					drawLine(pCanvas, pPaint, tCurrentYPosition, tTempYPosition, tCurrentXPosition, tTempXPosition, tCulOffset, tRectF);
					pPaint.setColor(m_color2);
					drawLine(pCanvas, pPaint, tCurrentYPosition1, tTempYPosition1, tCurrentXPosition1, tTempXPosition1, tCulOffset, tRectF);
				}
				else
				{
					tStartDraw = true;
				}

				if (tDataList.get(i).m_bDrawDot)
				{
					pPaint.setColor(tDotColor);
					pCanvas.drawCircle(tCurrentXPosition, tCurrentYPosition, tLineWidth * 2, pPaint);
				}

				if (i == minCount - 1)
				{
					if (candle != null)
					{
						m_lastMacd = FormatUtil.getFormatString(tMacd, m_bDigit + 1);
						m_lastHist = FormatUtil.getFormatString(tHist, m_bDigit + 1);
						m_lastSignal = FormatUtil.getFormatString(tSignal, m_bDigit + 1);
					}
				}
			}

		}

		RectF tLayerRect = tCoordinate.getLayerRectF();
		setCrossData(pCanvas, pPaint, tTimeText, tValueText, new Point(tXPoint, pPoint.y));


	}

	private void drawLine(Canvas pCanvas, Paint pPaint, float tCurrentYPosition, float tTempYPosition, float tCurrentXPosition, float tTempXPosition, int tCulOffset, RectF tRectF)
	{
		pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);

		//如果有可能超出图的范围，用下面的方法
//		boolean tTempUpper = (tRectF.top - tCulOffset) <= tTempYPosition ? false : true;
//		boolean tTempLowwer = (tRectF.bottom + tCulOffset) >= tTempYPosition ? false : true;
//		boolean tCurrentUpper = (tRectF.top - tCulOffset) <= tCurrentYPosition ? false : true;
//		boolean tCurrentLowwer = (tRectF.bottom + tCulOffset) >= tCurrentYPosition ? false : true;
//
//		if (!tTempUpper && !tTempLowwer && !tCurrentUpper && !tCurrentLowwer)
//		{
////						LogUtils.w("DrawLineA", "startX: " + tTempXPosition + " startY: " + tTempYPosition
////							+ " endX: " + tCurrentXPosition + " endY: " + tCurrentYPosition);
//
//			pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);
//		}
//		else if ((tTempUpper || tTempLowwer) && !tCurrentUpper && !tCurrentLowwer)
//		{
//			float middle;
//			if (tTempUpper)
//			{
//				middle = tRectF.top;
//			}
//			else
//			{
//				middle = tRectF.bottom;
//			}
//			float tTempX = (tCurrentXPosition - tTempXPosition) * getScale(tTempYPosition, tCurrentYPosition, middle) + tTempXPosition;
//
//			pCanvas.drawLine(tTempX, middle, tCurrentXPosition, tCurrentYPosition, pPaint);
//		}
//		else if ((tCurrentUpper || tCurrentLowwer) && !tTempUpper && !tTempLowwer)
//		{
//			float middle;
//			if (tCurrentUpper)
//			{
//				middle = tRectF.top;
//			}
//			else
//			{
//				middle = tRectF.bottom;
//			}
//			float tTempX = (tCurrentXPosition - tTempXPosition) * getScale(tTempYPosition, tCurrentYPosition, middle) + tTempXPosition;
//
//			pCanvas.drawLine(tTempXPosition, tTempYPosition, tTempX, middle, pPaint);
//		}
//		else
//		{
//		}
	}

	private String getDigitString(String value, int digit)
	{
		if (!TextUtils.isEmpty(value))
		{
			try
			{
				value = FormatUtil.getFormatString(Double.parseDouble(value), digit);
			}
			catch (Exception e)
			{
			}
		}
		else
		{
			value = "";
		}

		return value;
	}

	private float getScale(float start, float end, float middle)
	{
		return (start - middle) / (start - end);
	}

	private void resetIndicatorData()
	{
		m_macd = "";
		m_signal = "";
		m_hist = "";
		m_lastMacd = "";
		m_lastSignal = "";
		m_lastHist = "";
	}

	/**
	 * draw layer left－top text
	 * 获取指标值进行显示
	 *
	 * @param pCanvas
	 * @param pPaint
	 */
	@Override
	public void drawFloatIndicatorText(boolean longtouch, Canvas pCanvas, Paint pPaint)
	{

		if (!m_callback.needFloatIndicatorText())
		{
			return;
		}

		List<CandleData> tDataList = m_callback.getCandleDataList();
		if (tDataList == null || tDataList.size() == 0)
		{
			resetIndicatorData();
		}

		Coordinate tCoordinate = m_callback.getCoordinate();
		RectF tLayerRect = tCoordinate.getLayerRectF();

		float tLeftPadding = DimentionsUtil.dp2px(0);
		float tButtomPadding = DimentionsUtil.dp2px(1) + 1;
		float tWordPadding = DimentionsUtil.dp2px(10);

		String indicatorText0 = String.format("MACD(%s,%s,%s)", m_fastPeriod, m_slowPeriod, m_signalPeriod);
		String indicatorText1;
		String indicatorText2;
		String indicatorText3;
		if (longtouch)
		{
			indicatorText1 = "DIF:" + m_macd;
			indicatorText2 = "DEA:" + m_signal;
			indicatorText3 = "MACD:" + m_hist;
		}
		else
		{
			indicatorText1 = "DIF:" + m_lastMacd;
			indicatorText2 = "DEA:" + m_lastSignal;
			indicatorText3 = "MACD:" + m_lastHist;
		}
		pPaint.setAntiAlias(true);
		float textSize = DimentionsUtil.dp2px(10);
		pPaint.setTextSize(textSize);
		float tTxtWidth0 = pPaint.measureText(indicatorText0);
		float tTxtWidth1 = pPaint.measureText(indicatorText1);
		float tTxtWidth2 = pPaint.measureText(indicatorText2);

		pPaint.setColor(m_color0);
		pCanvas.drawText(indicatorText0, tLayerRect.left + tLeftPadding, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color1);
		pCanvas.drawText(indicatorText1, tLayerRect.left + tLeftPadding + tWordPadding + tTxtWidth0, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color2);
		pCanvas.drawText(indicatorText2, tLayerRect.left + tLeftPadding + tWordPadding * 2 + tTxtWidth0 + tTxtWidth1, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color3);
		pCanvas.drawText(indicatorText3, tLayerRect.left + tLeftPadding + tWordPadding * 3 + tTxtWidth0 + tTxtWidth1 + tTxtWidth2, tLayerRect.top + tButtomPadding + textSize, pPaint);

	}
}
